package com.open.pingban.utils;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.open.pingban.mode.MusicData;

import java.util.List;

/**
 * 播放器类 单例模式：封装了播放器的相关操作
 *
 * @author kymjs
 */
public class Player {
    private static Player player = new Player();
    private MediaPlayer media;
    private OnMediaPlayerLister mMediaPlayerLister;

    private int mode = Config.MODE_SEQUENCE; // 默认列表循环.
    private int playing = Config.PLAYING_STOP;

    //    private List<Music> list;
    List<MusicData.AudiosBean> list;
    private int position = 0;
    private Context context;

    private Player() {
    }

    public static Player getPlayer() {
        return player;
    }

    //    public List<Music> getList() {
//        return this.list;
//    }

    public List<MusicData.AudiosBean> getList() {
        return this.list;
    }

    public void setList( List<MusicData.AudiosBean> list1) {
        this.list = list1;
    }

    public int getListPosition() {
        return this.position;
    }

    public MusicData.AudiosBean getMusic() {
        MusicData.AudiosBean music = null;
        if (position >= list.size()) {
//            music = new Music();
//            music.setArtist(Config.ARTIST);
//            music.setTitle(Config.TITLE);
        } else {
            music = list.get(position);
        }
        return music;
    }

    public Player setMode(int mode) {
        this.mode = mode;
        mediaPlayerLister.onPlayListMode(this.media, this.mode);
        return this;
    }

    public int getMode() {
        return this.mode;
    }

    public int getPlaying() {
        return playing;
    }

    // 获取播放的音乐文件总时间长度
    public int getDuration() {
        int durat = 0;
        if (media != null) {
            durat = media.getDuration();
        }
        return durat;
    }

    // 获取当前播放音乐时间点
    public int getCurrentPosition() {
        int currentPosition = 0;
        if (media != null) {
            currentPosition = media.getCurrentPosition();
        }
        return currentPosition;
    }

    // 将音乐播放跳转到某一时间点,以毫秒为单位
    public Player seekTo(int msec) {
        if (media != null) {
            media.seekTo(msec);
        }
        return this;
    }

    public Player destroy() {
        if (media != null) {
            media.release();
            playing = Config.PLAYING_STOP;
            mMediaPlayerLister.onPlayState(media, playing);
        }
        if (mProssbarHandler != null) {
            mProssbarHandler.removeCallbacksAndMessages(null);
        }
        return this;
    }

    public Player stop() {
        if (playing != Config.PLAYING_STOP) {
            media.reset();
            playing = Config.PLAYING_STOP;
            mMediaPlayerLister.onPlayState(media, playing);
            context.sendBroadcast(new Intent(Config.RECEIVER_MUSIC_CHANGE));
        }
        return this;
    }

    public Player pause() {
        if (playing != Config.PLAYING_PAUSE) {
            media.pause();
            playing = Config.PLAYING_PAUSE;
            mMediaPlayerLister.onPlayState(media, playing);
            context.sendBroadcast(new Intent(Config.RECEIVER_MUSIC_CHANGE));
        }
        return this;
    }

    // 正在暂停，即将开始继续播放
    public MusicData.AudiosBean replay() {
        if (playing != Config.PLAYING_PLAY) {
            media.start();
            playing = Config.PLAYING_PLAY;
            mMediaPlayerLister.onPlayState(media, playing);
            context.sendBroadcast(new Intent(Config.RECEIVER_MUSIC_CHANGE));
        }
        return list.get(position);
    }

    public MusicData.AudiosBean play(Context context, List<MusicData.AudiosBean> list, int position) {
        String path = list.get(position).getUrl();
        String startHead = path.startsWith("http") ? "" : "file://"; // 判断是否为网络地址.
        String playUrl = startHead + path;
        Uri uri = Uri.parse(playUrl);
        OPENLOG.D("uri:" + uri);

        try {
            /**
             *  这种方式，卡界面.
             */
            if (media != null && playing == Config.PLAYING_PLAY) {
                media.reset();
            }
            media = MediaPlayer.create(context, uri);
            media.start();
            this.list = list;
            this.position = position;
            this.context = context;
            media.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    Player.this.context.sendBroadcast(new Intent(
                            Config.RECEIVER_MUSIC_CHANGE));
                    /* 播放结束后继续播放(单曲循环等等) */
                    completion(Player.this.context, Player.this.list,
                            Player.this.position);
                    mMediaPlayerLister.onCompletion(mp);
                    /* 清除进度条Handler */
                    if (mProssbarHandler != null) {
                        mProssbarHandler.removeCallbacksAndMessages(null);
                    }
                }
            });
            media.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.d("hailongqiu", "onPrepared");
                    playing = Config.PLAYING_PLAY;
                    mMediaPlayerLister.onPlayState(mp, playing);
                    mMediaPlayerLister.onPrepared(mp);
                    /* 进度条显示进度 */
                    mProssbarHandler.sendEmptyMessageDelayed(-250, 10);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            OPENLOG.E("播放歌曲错误... ..." + e.getMessage());
        }
        return list.get(position);
    }

    public MusicData.AudiosBean next(Context context) {
        MusicData.AudiosBean music = null;
        if (list.size() < 1) {
            this.destroy();
        } else {
//            media.reset(); // 停止上一首
            position = (position + 1) % list.size();
            play(context, list, position);
            music = list.get(position);
        }
        return music;
    }

    public MusicData.AudiosBean previous(Context context) {
        MusicData.AudiosBean music = null;
        if (list.size() < 1) {
            this.destroy();
            music = null;
        } else {
//            media.reset(); // 停止上一首
            position = (position + list.size() - 1) % list.size();
            play(context, list, position);
            music = list.get(position);
        }
        return music;
    }

    public MusicData.AudiosBean completion(Context context, List<MusicData.AudiosBean> list, int position) {
        MusicData.AudiosBean music = null;
        switch (mode) {
            case Config.MODE_REPEAT_SINGLE:  // 单曲播放
                stop();
                break;
            case Config.MODE_REPEAT_ALL: // 单曲循环
                music = play(context, list, position);
                break;
            case Config.MODE_SEQUENCE: // 列表循环
                music = play(context, list, (position + 1) % list.size());
                break;
            case Config.MODE_RANDOM: // 随机循环
                music = play(context, list, (int) (Math.random() * list.size()));
                break;
            default:
                break;
        }
        return music;
    }

    public MediaPlayer getMediaPlayer() {
        return this.media;
    }

    Handler mProssbarHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (media != null && media.isPlaying()) {
                int pos = media.getCurrentPosition();
                mMediaPlayerLister.onProgress(media, pos);
                mProssbarHandler.sendEmptyMessageDelayed(-250, 1000);
            }
        }
    };

    private final OnMediaPlayerLister mediaPlayerLister = new OnMediaPlayerLister();

    /**
     * 监听进度.
     */
    public Player setOnMediaPlayerLister(OnMediaPlayerLister lister) {
        if (lister == null) {
            lister = mediaPlayerLister; // 防止重复的去判断NULL.
        }
        this.mMediaPlayerLister = lister;
        return this;
    }

    public static class OnMediaPlayerLister {
        public void onProgress(MediaPlayer mp, int value) {
        }

        public void onPlayState(MediaPlayer mp, int state) {
        }

        public void onPlayListMode(MediaPlayer mp, int mode) {
        }

        public void onCompletion(MediaPlayer mp) {
        }

        public void onPrepared(MediaPlayer mp) {
        }
    }

    /**
     * 将秒转换成小时:分:秒的样式.
     * return hour:min:sec
     */
    public String sec2Time(int value) {
        value = value / 1000;
        String time = "%02d:%02d:%02d";
        int hour = 0;
        int min = 0;
        int sec = 0;
        hour = value / 3600;
        min = (value % 3600) / 60;
        sec = (value % 3600) % 60;
        time = String.format(time, hour, min, sec);
        return time;
    }

}
